import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/word.dart';
import '../models/learning_record.dart';
import '../models/wrong_question.dart';
import '../../core/constants.dart';

// StorageService Provider
final storageServiceProvider = Provider<StorageService>((ref) {
  throw UnimplementedError('StorageService must be overridden in main.dart');
});

class StorageService {
  SharedPreferences? _prefs;

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  SharedPreferences get prefs {
    if (_prefs == null) {
      throw Exception('StorageService not initialized. Call init() first.');
    }
    return _prefs!;
  }

  Future<List<String>> getFavoriteWords() async {
    final List<String> favorites = prefs.getStringList(AppConstants.KEY_FAVORITE_WORDS) ?? [];
    return favorites;
  }

  Future<void> addFavoriteWord(String wordId) async {
    final List<String> favorites = await getFavoriteWords();
    if (!favorites.contains(wordId)) {
      favorites.add(wordId);
      await prefs.setStringList(AppConstants.KEY_FAVORITE_WORDS, favorites);
    }
  }

  Future<void> removeFavoriteWord(String wordId) async {
    final List<String> favorites = await getFavoriteWords();
    favorites.remove(wordId);
    await prefs.setStringList(AppConstants.KEY_FAVORITE_WORDS, favorites);
  }

  Future<List<LearningRecord>> getLearningRecords() async {
    final List<String> recordsJson = prefs.getStringList(AppConstants.KEY_LEARNING_RECORDS) ?? [];
    return recordsJson.map((json) => LearningRecord.fromJson(jsonDecode(json))).toList();
  }

  Future<void> addLearningRecord(LearningRecord record) async {
    final List<LearningRecord> records = await getLearningRecords();
    records.add(record);
    final List<String> recordsJson = records.map((record) => jsonEncode(record.toJson())).toList();
    await prefs.setStringList(AppConstants.KEY_LEARNING_RECORDS, recordsJson);
  }



  // 学习状态相关方法
  Future<Set<String>> getMasteredWords() async {
    final List<String> masteredList = prefs.getStringList(AppConstants.KEY_MASTERED_WORDS) ?? [];
    return masteredList.toSet();
  }

  Future<void> saveMasteredWords(Set<String> masteredWords) async {
    await prefs.setStringList(AppConstants.KEY_MASTERED_WORDS, masteredWords.toList());
  }

  Future<void> addMasteredWord(String wordId) async {
    final Set<String> masteredWords = await getMasteredWords();
    masteredWords.add(wordId);
    await saveMasteredWords(masteredWords);
  }

  Future<int> getCurrentLearningIndex() async {
    return prefs.getInt(AppConstants.KEY_CURRENT_LEARNING_INDEX) ?? 0;
  }

  Future<void> saveCurrentLearningIndex(int index) async {
    await prefs.setInt(AppConstants.KEY_CURRENT_LEARNING_INDEX, index);
  }

  Future<Map<String, dynamic>?> getLearningSessionState() async {
    final String? sessionJson = prefs.getString(AppConstants.KEY_LEARNING_SESSION_STATE);
    if (sessionJson == null) return null;
    return jsonDecode(sessionJson);
  }

  Future<void> saveLearningSessionState(Map<String, dynamic> sessionState) async {
    await prefs.setString(AppConstants.KEY_LEARNING_SESSION_STATE, jsonEncode(sessionState));
  }

  Future<void> clearLearningSessionState() async {
    await prefs.remove(AppConstants.KEY_LEARNING_SESSION_STATE);
  }

  // 重置学习进度（用于测试）
  Future<void> resetLearningProgress() async {
    await prefs.remove(AppConstants.KEY_MASTERED_WORDS);
    await prefs.remove(AppConstants.KEY_CURRENT_LEARNING_INDEX);
    await prefs.remove(AppConstants.KEY_LEARNING_SESSION_STATE);
    await prefs.remove(AppConstants.KEY_LEARNING_RECORDS);
  }

  // 调试方法：打印存储的数据
  Future<void> debugPrintStoredData() async {
    final masteredWords = await getMasteredWords();
    final currentIndex = await getCurrentLearningIndex();
    final records = await getLearningRecords();
    final wrongQuestions = await getWrongQuestions();
    
    print('=== Storage Debug Info ===');
    print('Mastered Words Count: ${masteredWords.length}');
    print('Mastered Words: ${masteredWords.toList()}');
    print('Current Learning Index: $currentIndex');
    print('Learning Records Count: ${records.length}');
    if (records.isNotEmpty) {
      print('Latest Record: ${records.last.wordId} - ${records.last.isCorrect}');
    }
    print('Wrong Questions Count: ${wrongQuestions.length}');
    if (wrongQuestions.isNotEmpty) {
      print('Latest Wrong Question: ${wrongQuestions.last.wordId} - attempts: ${wrongQuestions.last.attemptCount}');
    }
    print('=========================');
  }

  // 错题本相关方法
  Future<List<WrongQuestion>> getWrongQuestions() async {
    final List<String> wrongQuestionsJson = prefs.getStringList(AppConstants.KEY_WRONG_QUESTIONS) ?? [];
    return wrongQuestionsJson.map((json) => WrongQuestion.fromJson(jsonDecode(json))).toList();
  }

  Future<void> addWrongQuestion(WrongQuestion wrongQuestion) async {
    final List<WrongQuestion> wrongQuestions = await getWrongQuestions();
    
    // 检查是否已存在相同的错题
    final existingIndex = wrongQuestions.indexWhere((q) => q.wordId == wrongQuestion.wordId);
    
    if (existingIndex != -1) {
      // 如果已存在，增加尝试次数
      wrongQuestions[existingIndex] = wrongQuestions[existingIndex].copyWith(
        attemptCount: wrongQuestions[existingIndex].attemptCount + 1,
        wrongAt: wrongQuestion.wrongAt,
        selectedIndex: wrongQuestion.selectedIndex,
      );
    } else {
      // 如果不存在，添加新的错题
      wrongQuestions.add(wrongQuestion);
    }
    
    final List<String> wrongQuestionsJson = wrongQuestions.map((q) => jsonEncode(q.toJson())).toList();
    await prefs.setStringList(AppConstants.KEY_WRONG_QUESTIONS, wrongQuestionsJson);
  }

  Future<void> removeWrongQuestion(String wordId) async {
    final List<WrongQuestion> wrongQuestions = await getWrongQuestions();
    wrongQuestions.removeWhere((q) => q.wordId == wordId);
    final List<String> wrongQuestionsJson = wrongQuestions.map((q) => jsonEncode(q.toJson())).toList();
    await prefs.setStringList(AppConstants.KEY_WRONG_QUESTIONS, wrongQuestionsJson);
  }

  Future<bool> hasWrongQuestion(String wordId) async {
    final List<WrongQuestion> wrongQuestions = await getWrongQuestions();
    return wrongQuestions.any((q) => q.wordId == wordId);
  }

  Future<void> clearWrongQuestions() async {
    await prefs.remove(AppConstants.KEY_WRONG_QUESTIONS);
  }
} 